package com.lms.mapper;

import java.sql.*;

public class SQLConnect {
    private Connection connection = null;//连接对象
    private Statement statement = null;//语句对象

    public SQLConnect() throws Exception {
        String driver = "com.mysql.cj.jdbc.Driver";//驱动类名称

        String url = "jdbc:mysql://47.115.207.238:3306/lms?useUnicode=true&characterEncoding=utf8";//要连接的数据库
        String username = "aliyun";//用户
        String password = "Pass@123456";//密码

        Class.forName(driver);//加载驱动
        connection = DriverManager.getConnection(url, username, password);
        statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
    }

    public SQLConnect(String ip, String host, String db_name, String username, String password) throws Exception {
        String driver = "com.mysql.cj.jdbc.Driver";//驱动类名称

        String url = "jdbc:mysql://"+ip+":"+host+"/"+db_name+"?useUnicode=true&characterEncoding=utf8";//要连接的数据库


        Class.forName(driver);//加载驱动
        connection = DriverManager.getConnection(url, username, password);
        statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
    }


    public ResultSet executeQuery(String sql) {
        ResultSet resultSet = null;
        try {
            resultSet = statement.executeQuery(sql);
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
        return resultSet;
    }

    public PreparedStatement prepareStatement(String sql) {
        try {
            return connection.prepareStatement(sql);
        } catch (SQLException e) {
            e.printStackTrace(System.err);
            return null;
        }
    }

    public int executeUpdate(String sql) {
        try {
            return statement.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace(System.err);
            return 0;
        }
    }

    public boolean isConnected() {
        return connection != null;
    }


    public void close() {

        if (statement != null) {
            try {
                statement.close();
            } catch (Exception e) {
                e.printStackTrace(System.err);
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace(System.err);
            }
        }

    }

}
